package jp.co.cos.ittrick.channel.controller.admin;

import java.util.ArrayList;
import java.util.List;

import jp.co.cos.ittrick.channel.model.ApplicationModel;
import jp.co.cos.ittrick.channel.service.ApplicationService;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;

import com.google.appengine.api.datastore.Text;

/**
 * カテゴリ・Class リスト
 * @author takahara
 *
 */
public class ApplicationUpdateController extends Controller {

    private ApplicationService applicationService;

    public ApplicationUpdateController() {
        applicationService = new ApplicationService();
    }

    @Override
    public Navigation run() throws Exception {

        boolean isNewFlg = false;

        String applicationId = asString("applicationId");
        String applicationName = asString("applicationName");
        String description = asString("description");
        String applContent = asString("applContent");
        String twitterAccount = asString("twitterAccount");
        String applLogoImageCode = asString("applLogoImageCode");
        String applBackgroundImageCode = asString("applBackgroundImageCode");
        String keyWords = asString("keyWord");

        // キーワードリストの設定
        List<String> keyWordList = new ArrayList<String>();
        if(keyWords != null && keyWords.length() > 0) {
            String[] keyWordsTmp = keyWords.split(",");
            for(String keyWord: keyWordsTmp) {
                if(!keyWord.isEmpty()) {
                    keyWordList.add(keyWord);
                }
            }
        }

        ApplicationModel model = applicationService.getApplicationModel();
        if(model == null) {
            model = new ApplicationModel();
            isNewFlg = true;
        }

        model.setApplicationId(applicationId);
        model.setApplicationName(applicationName);
        model.setDescription(description);
        model.setTwitterAccount(twitterAccount);
        model.setApplLogoImageCode(applLogoImageCode);
        model.setApplBackgroundImageCode(applBackgroundImageCode);
        model.setKeyWordList(keyWordList);
        model.setApplContent(new Text(applContent));

        if(isNewFlg) {
            applicationService.insert(model);
        }else {
            applicationService.update(model);
        }

        // 検索し直す
        model = applicationService.getApplicationModel();
        requestScope("applicationModel", model);

        return redirect("/admin/application");
    }
}
